<template>
    <div class="text-center" style="calc(100vh);height: calc(100vh)">
      <el-card style="width: calc(70vh);height: calc(50vh)">
        <el-form label-position="left" :model="userForm" status-icon :rules="rules2" ref="userForm" label-width="70px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="name">
            <el-input type="text" v-model="userForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('userForm')">登录</el-button>
            <el-button @click="resetForm('userForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
</template>

<script>
import {fetch} from '@/utils/http'
import {mapActions, mapGetters} from 'vuex'
import {setUser, getUser} from '@/utils/session'
export default {
  data () {
    var validateUsername = (rule, value, callback) => {
      let pattern = /^[a-zA-Z]\w{4,9}/
      if (!pattern.test(value)) {
        callback(new Error('请输入用户名以字母开头(总数为5-10位字母数字下划线)'))
      } else {
        if (this.userForm.name !== '') {
          // 这个是在此规则校验完了以后，再进行相关字段规则进行校验
          // this.$refs.userForm.validateField('name')
        }
        callback()
      }
    }
    var validatePassword = (rule, value, callback) => {
      // 校验密码
      let pattern = /[a-zA-Z1-9@*_]{6,12}/
      if (pattern.test(value)) {
        callback()
      } else {
        callback(new Error('请输入6-12的数字字母下划线'))
      }
    }
    return {
      userForm: {
        username: '',
        password: ''
      },
      rules2: {
        username: [
          { validator: validateUsername, trigger: 'blur' }
        ],
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          fetch('token/login', this.userForm).then((res) => {
            if (res.status === 200) {
              setUser(res.data)
              _this.setToken(res.data.access_token)
              _this.setUserName(res.data.username)
              /// 再一请求
              fetch('upms/user/current', {'access_token': this.token}).then((res) => {
                if (res.status === 200) {
                  let user = getUser()
                  // Object.assign(user, res.data)
                  res.data['access_token'] = user.access_token
                  setUser(res.data)
                  _this.$router.push({path: '/demo/home'})
                  // this.setUserId(res.data.id)
                  // this.setResources(this.resources)
                } else {
                  _this.$message.error('请重新登录!')
                }
              })
            } else {
              this.$message.error('错误:' + res.message)
            }
          })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    ...mapActions(['setToken', 'setUserName', 'setUserId', 'setRoles', 'setResources'])
  },
  computed: {
    ...mapGetters(['username', 'userId', 'token', 'roles', 'resources'])
  }
}
</script>

<style scoped>
  .text-center {
    display:flex;
    justify-content:center;
    align-items:center;
  }
</style>
